<template>
    <div class="effectChain" @click="handleGlobalClick">
        <div class="title-bar">
            <div class="title">1E Unsaved*</div>
            <div class="controls">
                <span>⟳</span>
                <span>A</span>
                <span>☰</span>
            </div>
        </div>

        <div class="main-content">
            <div class="sidebar">
                <button v-for="i in 5" :key="`input-${i}`" class="InputBtn"
                    @click="toggleSidebar('input', i)">+</button>
            </div>

            <div class="content">
                <div class="content-line">
                    <div class="hidden-buttons-container">
                        <div v-for="i in 40" :key="`hidden-${i}`" class="hidden-button-wrapper"
                            @click.stop="toggleSidebar('module', i)" :draggable="!!buttonContents[i - 1]"
                            @dragstart="dragStart($event, i)" @dragend="dragEnd" @dragover="dragOver($event, i)"
                            @dragenter="dragEnter($event, i)" @dragleave="dragLeave" @drop="handleDrop($event, i)">
                            <img v-if="buttonContents[i - 1]" :src="buttonContents[i - 1]" alt="Module"
                                class="hidden-button-image">
                            <button
                                v-else-if="activeButton && activeButton.type === 'module' && activeButton.index === i"
                                class="hidden-button visible">+</button>
                            <button v-else class="hidden-button">+</button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="sidebar sidebar-right-buttons">
                <button v-for="i in 5" :key="`output-${i}`" class="OutputBtn"
                    @click="toggleSidebar('output', i)">+</button>
            </div>

            <div v-for="i in 5" :key="`line-${i}`" :id="`line${i}`" class="connection-line"></div>
        </div>

        <div id="sidebar-input" class="sidebar-panel" :class="{ visible: sidebarStates.input }">
            <ul>
                <li v-for="i in 5" :key="`input-${i}`" @click="replaceButtonContent('input', i)">Input {{ i }}</li>
            </ul>
        </div>

        <div id="sidebar-output" class="sidebar-panel" :class="{ visible: sidebarStates.output }">
            <ul>
                <li v-for="i in 5" :key="`output-${i}`" @click="replaceButtonContent('output', i)">Output {{ i }}</li>
            </ul>
        </div>

        <div id="sidebar-module" class="sidebar-panel" :class="{ visible: sidebarStates.module }">
            <ul>
                <li v-for="(module, index) in modules" :key="index" @click="replaceButtonContent('module', module)">
                    <img :src="require(`@/assets/${module.img}.png`)" :alt="module.name"> <span
                        style="margin-left: 20px;">{{ module.name }}</span>
                </li>
                <li @click="deleteModule"><span style="margin-left: 20px;">DELETE</span></li>
            </ul>
        </div>
    </div>
</template>

<script>

export default {
    name: 'AudioInterface',
    data() {
        return {
            modules: [
                { name: 'AMP', img: 'amp' },
                { name: 'IR', img: 'ir' },
                { name: 'MOD', img: 'mod' },
                { name: 'RVB', img: 'rvb' },
                { name: 'VOL', img: 'vol' },
            ],
            sidebarStates: {
                input: false,
                output: false,
                module: false,
            },
            activeButton: null,
            draggedElement: null,
            buttonContents: new Array(40).fill(null),
            draggedIndex: null,
        }
    },
    mounted() {
        this.$nextTick(() => {
            this.positionAllLines();
            window.addEventListener('resize', this.positionAllLines);
            document.addEventListener('click', this.handleGlobalClick);
        });
    },
    beforeUnmount() {
        window.removeEventListener('resize', this.positionAllLines);
        document.removeEventListener('click', this.handleGlobalClick);
    },
    methods: {
        positionLine(lineId, leftBtnIndex, rightBtnIndex) {
            const line = document.getElementById(lineId);
            const btnLeft = document.querySelectorAll('.sidebar .InputBtn')[leftBtnIndex];
            const btnRight = document.querySelectorAll('.sidebar-right-buttons .OutputBtn')[rightBtnIndex];
            const container = document.querySelector('.content');

            const rectLeft = btnLeft.getBoundingClientRect();
            const rectRight = btnRight.getBoundingClientRect();
            const rectContent = container.getBoundingClientRect();

            const centerLeftX = rectLeft.left + rectLeft.width / 2;
            const centerLeftY = rectLeft.top + rectLeft.height / 2 - rectContent.top + 9;
            const centerRightX = rectRight.left + rectRight.width / 2;
            const centerRightY = rectRight.top + rectRight.height / 2;


            console.log('Positioning line:', line, rectLeft, rectRight, rectContent);

            line.style.top = `${centerLeftY}px`;
            line.style.left = `${centerLeftX}px`;
            line.style.width = `${centerRightX - centerLeftX}px`;
            line.style.height = '2px';
            line.style.zIndex = 1;
        },
        positionAllLines() {
            for (let i = 1; i <= 5; i++) {
                this.positionLine(`line${i}`, i - 1, i - 1);
            }
        },

        handleGlobalClick(event) {
            // 检查点击是否发生在侧边栏之外
            if (!event.target.closest('.sidebar-panel')) {
                this.closeSidebars();
            }
        },

        closeSidebars() {
            Object.keys(this.sidebarStates).forEach(key => {
                this.sidebarStates[key] = false;
            });
            this.activeButton = null;
        },

        toggleSidebar(type, index) {
            if (this.activeButton && this.activeButton.type === type && this.activeButton.index === index) {
                this.closeSidebars();
            } else {
                this.closeSidebars();
                this.sidebarStates[type] = true;
                this.activeButton = { type, index };
            }
        },
        deleteModule() {
            if (this.activeButton && this.activeButton.type === 'module') {
                const buttonIndex = this.activeButton.index - 1;
                this.buttonContents[buttonIndex] = null;
                this.sidebarStates.module = false;
                this.activeButton = null;
            }
        },
        dragStart(event, index) {
            if (this.buttonContents[index - 1]) {
                this.draggedElement = event.target;
                this.draggedIndex = index - 1;
                event.dataTransfer.effectAllowed = 'move';
                event.dataTransfer.setData('text/plain', index.toString());
                setTimeout(() => {
                    event.target.style.opacity = '0.5';
                }, 0);
            } else {
                event.preventDefault();
            }
        },

        dragEnd(event) {
            event.target.style.opacity = '1';
            this.draggedElement = null;
            this.draggedIndex = null;
        },

        dragEnter(event, index) {
            if (this.draggedIndex !== index - 1) {
                event.target.classList.add('droppable');
            }
        },

        // 拖动经过目标元素时的处理函数
        dragOver(event) {
            event.preventDefault();
            event.target.classList.add('drag-over');
        },

        dragLeave(event) {
            event.target.classList.remove('droppable');
            event.target.classList.remove('drag-over');
        },

        handleDrop(event, index) {
            event.preventDefault();
            const targetIndex = index - 1;
            event.target.classList.remove('droppable');
            event.target.classList.remove('drag-over');

            if (this.draggedIndex !== null && this.draggedIndex !== targetIndex) {
                // 交换两个位置的内容
                const temp = this.buttonContents[this.draggedIndex];

                this.buttonContents[this.draggedIndex] = null;
                this.buttonContents[targetIndex] = temp;
            }
        },

        replaceButtonContent(type, content) {
            if (!this.activeButton) return;

            if (type === 'module') {
                const buttonIndex = this.activeButton.index - 1;
                if (content === 'DELETE') {
                    this.buttonContents[buttonIndex] = null;
                } else {
                    this.buttonContents[buttonIndex] = require(`@/assets/${content.img}.png`);
                }
            } else if (type === 'input') {
                const button = document.querySelectorAll('.sidebar .InputBtn')[this.activeButton.index - 1];
                button.textContent = `Input ${content}`;
            } else if (type === 'output') {
                const button = document.querySelectorAll('.sidebar-right-buttons .OutputBtn')[this.activeButton.index - 1];
                button.textContent = `Output ${content}`;
            }

            this.closeSidebars();
        },
        handleGlobalClick(event) {
            const inputSidebar = document.getElementById('sidebar-input');
            const outputSidebar = document.getElementById('sidebar-output');
            const moduleSidebar = document.getElementById('sidebar-module');

            // 检查点击是否发生在侧边栏之外
            if (!event.target.closest('.sidebar-panel') && !event.target.closest('.sidebar button')) {
                if (inputSidebar && inputSidebar.classList.contains('visible')) {
                    this.sidebarStates.input = false;
                }
                if (outputSidebar && outputSidebar.classList.contains('visible')) {
                    this.sidebarStates.output = false;
                }
                if (moduleSidebar && moduleSidebar.classList.contains('visible')) {
                    this.sidebarStates.module = false;
                }
                this.activeButton = null;
            }
        },
    }
}
</script>

<style scoped>
html,
body,
#app {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    overflow: hidden;
    box-sizing: border-box;
}

.effectChain {
    background-color: #333;
    color: white;
    height: 100%;
    width: 100%;
    font-family: Arial, sans-serif;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
}

.title-bar {
    display: flex;
    align-items: center;
    padding: 10px;
    background-color: #444;
    flex-shrink: 0;
    height: 80px;
}

.title {
    font-size: 3em;
    flex: 1;
}

.controls {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-right: 0px;
}

.controls span {
    background: none;
    border: none;
    margin: 10px;
    color: white;
    font-size: 2.4em;
    cursor: pointer;
}

.main-content {
    display: flex;
    flex: 1;
    padding: 10px;
    position: relative;
}

.sidebar {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    width: 100px;
    flex-shrink: 0;
}

.sidebar button {
    background-color: #555;
    border: none;
    color: white;
    padding: 10px;
    margin: 15px;
    border-radius: 10px;
    cursor: pointer;
    font-size: 2em;
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
}

.sidebar button.InputBtn {
    background-color: #777;
    margin-left: 30px;
}

.sidebar button.OutputBtn {
    background-color: #777;
    margin-right: 30px;
}

.content {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
}

.content-line {
    display: flex;
    align-items: center;
    width: 100%;
    justify-content: space-between;
    z-index: 99;
}

.hidden-buttons-container {
    display: flex;
    flex-wrap: wrap;
    gap: 40px;
    /* 使用 gap 替代单独的 margin */
    justify-content: center;
    /* 居中对齐按钮 */
    width: 100%;
    position: absolute;
    top: 49.1%;
    left: 54%;
    transform: translate(-50%, -50%);
}

.hidden-button-wrapper {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;
}

.hidden-button-wrapper[draggable="true"] {
    cursor: move;
}

.droppable {
    border: 2px dashed #aaa;
}

.hidden-button {
    background-color: #555;
    border: none;
    color: white;
    width: 100%;
    height: 100%;
    border-radius: 10px;
    cursor: pointer;
    font-size: 2em;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
}

.hidden-button.visible {
    opacity: 1;
}

.hidden-button-image {
    width: 100%;
    height: 100%;
    object-fit: contain;
    border-radius: 10px;
}

.hidden-button i {
    margin-right: 5px;
}

.sidebar-panel li img {
    width: 60px;
    height: 60px;
    margin-left: 20px;
    vertical-align: middle;
}

.hidden-button img {
    width: 80px;
    height: 80px;
}

.sidebar-panel {
    position: fixed;
    top: 0;
    right: -350px;
    width: 300px;
    height: 100%;
    background-color: #555;
    transition: right 0.3s;
    padding: 20px;
    box-shadow: -2px 0 5px rgba(0, 0, 0, 0.5);
    overflow-y: auto;
    z-index: 1000;
    margin-left: 20px;
}

.sidebar-panel.visible {
    right: 0;
}

.sidebar-panel ul {
    list-style-type: none;
    padding: 0;
}

.sidebar-panel li {
    margin: 10px 0;
    padding: 10px;
    background-color: #666;
    border-radius: 10px;
    margin-left: 15px;
    font-size: 1.5em;
    cursor: pointer;
    display: flex;
    align-items: center;
}

.sidebar-right-buttons {
    flex-shrink: 0;
    margin-left: 80px;
}

.connection-line {
    background-color: white;
    height: 2px;
    position: absolute;
    z-index: 1;
}

.drag-over {
    opacity: 1 !important;
    transition: opacity 0.3s ease;
    border: 2px dashed #aaa;
}
</style>
